<template>
  <div class="login-modal">
    <div class="mask" @click="close"></div>
    <div class="login-box">
      <img class="close" @click="close" src="../assets/img/close.png" alt="" />
      <ul class="title">
        <li :class="isShowForm ? 'active' : ''" @click="isShowForm = true">
          手机号码登录
        </li>
        <li style="margin: -2px 10px 0; cursor: auto">|</li>
        <li :class="!isShowForm ? 'active' : ''" @click="toShowWeixin">
          微信扫码登录
        </li>
      </ul>
      <div class="body">
        <div class="form" v-show="isShowForm">
          <div class="input-group uname">
            <input
              ref="phone"
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNum"
            />
          </div>
          <div class="input-group mb20">
            <slide-verify
              :l="42"
              :r="20"
              :w="360"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>

          <div class="input-group code mb20">
            <input
              type="text"
              v-model="SMScode"
              placeholder="请输入短信验证码"
            />
            <div class="btn else" :class="isShowCount ? 'has-count' : ''">
              <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
              <span v-show="isShowCount">{{ count }} s</span>
            </div>
          </div>
          <div class="btn" @click="submitLogin">登录</div>
        </div>
        <!-- 加上id weixin-->
        <div class="wx-qrcode" v-show="!isShowForm" id="weixin">微信二维码</div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import {
  SendSMSAPI,
  PhoneLoginAPI,
  BindPhoneAPI
} from "@/request/api.js";
export default {
  data() {
    return {
      // 控制表单盒子的显示和隐藏
      isShowForm: true,
      // 图片验证码滑块文字
      msg: "向右滑动",
      // 用户输入的手机号
      phoneNum: "",
      // 用户输入的短信验证码
      SMScode: "",
      // 控制倒计时的显示和隐藏
      isShowCount: false,
      // 倒计时的数字
      count: 60,
    };
  },
  methods: {
    ...mapMutations({
      chanIsShowLoginModal: "showLoginModal/chanIsShowLoginModal",
      chanIsLogined: "loginStatus/chanIsLogined",
    }),
    ...mapActions({
      asyncChanIsShowToast: "showToast/asyncChanShoIswToast",
      asyncChanUserInfo: "userInfo/asyncChanUserInfo"
    }),
    toShowWeixin() {
      // 切换到展示二维码的界面
      this.isShowForm = false;
      // 获取二维码
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://192.168.199.102:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQo=",
      });
    },
    countDown() {
      let timer = setInterval(() => {
        this.count--;
        // 每一次count的变化,都需要验证是不是到0了,
        // 如果到0了,1关闭定时器,2隐藏倒计时文字,3初始化count,变成最大值60
        if (this.count === 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 60;
        }
      }, 1000);
    },
    verifyFn() {
      // 这个方法用来 验证手机号和滑块拼图

      // 1 验证用户输入的手机号码格式是否正确, 如果不正确,就return
      // if(!正则对象.test(用户输入的信息)){
      if (!validatePhoneNumber(this.phoneNum)) {
        this.asyncChanIsShowToast({
          msg: "请输入正确的手机号码!",
          type: "warning",
        });
        // 给用户直接聚焦
        this.$refs.phone.focus();
        return false;
      }

      // 2 验证滑块拼图验证码, 如果不通过, 就return
      if (this.msg === "再试一次" || this.msg === "向右滑动") {
        this.asyncChanIsShowToast({
          msg: "请滑动滑块至正确位置!",
          type: "warning",
        });
        return false;
      }

      return true;
    },
    async getSMScode() {
      // 点击获取短信验证执行这里的的代码
      // 前两步的验证(手机号和滑块拼图)
      if (!this.verifyFn()) {
        return;
      }

      // 3 发送短信验证码---就是一个请求, 把倒计时显示出来
      // SendSMSAPI({
      //   phone:this.phoneNum.trim(),
      // }).then(res=>{
      //     if(res.code==0){
      //       // 成功执行这里的代码
      //       // 显示倒计时
      //       this.isShowCount=true;
      //       // 进行倒计时
      //       this.countDown()
      //   }else{
      //     // 失败时候提示用户有问题
      //     alert(res.message)
      //   }
      // }).catch(err=>{
      //   console.log(err);
      // })
      let res = await SendSMSAPI({
        phone: this.phoneNum.trim(),
      });

      if (!res) return;
      this.asyncChanIsShowToast({
        msg: "短信验证码发送成功!",
        type: "success",
      });
      console.log("---", res);
      // 成功执行这里的代码
      // 显示倒计时
      this.isShowCount = true;
      // 进行倒计时
      this.countDown();
    },
    close() {
      // 隐藏登录模态窗口,本质上修改Vuex中的 isShowLoginModal的值变成false
      this.chanIsShowLoginModal(false);
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    async submitLogin() {
      // 点击登录按钮执行的代码

      // 1 手机号码的验证
      // 2 图片滑块验证码的验证
      if (!this.verifyFn()) {
        return;
      }

      // 3 验证用户输入的验证码是不是为空,为空就return
      if (!this.SMScode.trim()) {
        this.asyncChanIsShowToast({
          msg: "请输入短信验证码!",
          type: "warning",
        });
        return;
      }

      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindPhoneAPI({
          verifyCode: this.SMScode.trim(),
          phone: this.phoneNum.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
        });
      }

      // 通过验证,发起登录请求

      console.log(res);
      if (!res) return;
      // 分析登录成功之后的逻辑
      // 1 提示用户登录成功
      this.asyncChanIsShowToast({
        msg: "登录成功!",
        type: "success",
      });
      // 2 关闭登录窗口
      this.chanIsShowLoginModal(false);
      // 3 保存token值到localStorage中
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 4 登录状态的切换 (隐藏登录按钮展示购物车按钮, 用户名昵称头像)
      this.chanIsLogined(true);
      if (uuid) {
        localStorage.removeItem("uuid");
        this.$$router.push(this.$route.path);
      }
      //
      this.asyncChanUserInfo()
    },
  },
};
</script>
<style lang = "less" scoped>
@import "../assets/css/global.less";

.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;

    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }

    .title {
      display: flex;
      justify-content: center;
      padding: 45px 0 30px;
      color: #ccc;
      font-size: 18px;
      li {
        cursor: pointer;
      }
      .active {
        color: #333;
      }
    }

    .body {
      width: 360px;
      margin: 0 auto;

      .form {
        .uname {
          margin-bottom: 5px;
        }
        .input-group {
          display: flex;

          input {
            height: 48px;
            width: 100%;
            text-indent: 10px;
            border: 1px solid #ccc;
          }
        }
        .code input {
          width: 260px;
          margin-right: 8px;
        }

        .code .btn {
          flex: 1;
        }
        .btn {
          height: 50px;
          line-height: 50px;
          background-color: @base-color;
          color: #fff;
          text-align: center;
          cursor: pointer;
        }
        .else {
          border-radius: 10%;
        }
        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}

#weixin {
  display: flex;
  justify-content: center;
  margin-top: -10px;
}
</style>